# -*- coding: utf-8 -*-

# Description: Summarizes values of a raster within the zones of
#              another dataset and reports the results to a table.
# Requirements: Spatial Analyst Extension

# Import system modules

import os
from multiprocessing import Process
import re
import time
import arcpy
from arcpy.sa import *

root_in_path = u"E:\\毕设数据\\WuhanNDVI\\"
root_out_path = u"E:\\毕设数据\\WuhanNDVI_DBF\\"
qu_tif_root = u"E:\\毕设数据\\WuhanQuNDVI\\"

using_type_tif_root = u"E:\\毕设数据\\UsingTypeNDVI\\"
vegetation_type_tif_root = u"E:\\毕设数据\\VegetationTypeNDVI\\"


def img_value_to_table(ImgFile, TableFile):
    inData = ImgFile
    inRaster = ImgFile
    zoneField = "value"
    outTable = TableFile
    arcpy.CheckOutExtension("Spatial")
    ZonalStatisticsAsTable(inData, zoneField, inRaster,
                           outTable, "NODATA", "ALL")


def file_filter(folder):
    """返回一个文件夹中所有tif文件绝对路径"""
    files = []
    r_files = os.listdir(folder)

    for i in r_files:
        if i.endswith(".tif"):
            files.append(os.path.join(folder, i))
    return files


def extract_wuhan():
    in_folders = []
    for x in os.listdir(root_in_path):
        if os.path.isdir(os.path.join(root_in_path, x)):
            in_folders.append(os.path.join(root_in_path, x))

    for i in in_folders:
        if not os.path.exists(os.path.join(root_out_path, "DBF_" + i[-4:])):
            os.makedirs(os.path.join(root_out_path, "DBF_" + i[-4:]))
        out_path = os.path.join(root_out_path, "DBF_" + i[-4:])
        tif = file_filter(i)
        for t in tif:
            out_file_name = re.search(".*\\\(.*)\.tif", t).group(1).replace('.', '_').replace('-', '_')
            out_table = os.path.join(out_path, out_file_name + ".dbf")
            if os.path.exists(out_table):
                print out_table + " exist !"
                continue
            else:
                img_value_to_table(t, out_table)
                print t + " OK !"

def extract_qu(qu_dir, mode=1):
    year_dirs = os.listdir(qu_dir)
    in_dirs = []
    if mode==1:
        root_out = u"E:\\毕设数据\\QuNDVI_DBF\\"
    elif mode==2:
        root_out = u"E:\\毕设数据\\UsingTypeNDVI_DBF\\"
    elif mode==3:
        root_out = u"E:\\毕设数据\\VegetationTypeNDVI_DBF\\"
    else:
        raise ValueError

    for i in year_dirs:
        in_dirs.append(os.path.join(qu_dir, i))
        # out_path = os.path.join(os.path.join(root_out, os.path.basename(qu_dir)), "DBF_" + i[-4:])
        # if not os.path.exists(out_path):
        #     os.makedirs(out_path)
    for j in in_dirs:
        out_path = os.path.join(os.path.join(root_out, os.path.basename(qu_dir)), "DBF_" + j[-4:])

        if not os.path.exists(out_path):
            os.makedirs(out_path)
        tif = file_filter(j)
        # print tif
        for t in tif:
            out_file_name = re.search(".*\\\(.*)\.tif", t).group(1).replace('.', '_').replace('-', '_')
            out_table = os.path.join(out_path, out_file_name + ".dbf")
            if os.path.exists(out_table):
                print out_table + " exist !"
                continue
            else:
                img_value_to_table(t, out_table)
                print t + " OK !"


def run(ndvi_root, mode):
    """
    ndvi root = qu_tif_root, mode=1, 按行政区处理
    ndvi root = using_type_tif_root, mode=2, 按土地利用类型处理
    ndvi root = vegetation_type_tif_root, mode=3, 按土地利用类型处理

    :param ndvi_root:
    :param mode:
    :return:
    """
    qu = os.listdir(ndvi_root)
    plist = []
    for q in qu:
        arg = os.path.join(ndvi_root, q)

        p = Process(target=extract_qu, args=(arg,mode))
        plist.append(p)
    for i in plist:
        i.start()


if __name__ == '__main__':
    x = time.time()
    # run(ndvi_root=vegetation_type_tif_root, mode=3)
    extract_wuhan()
    # extract_qu(u"E:\\毕设数据\\WuhanQuNDVI\\江夏区")
    y = time.time()
    cost_time = (y - x) / 60
    print "cost time %.2f min" % cost_time
